import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/model/EcyApiCommonPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/ConsignComment.dart';
import '../model/ConsignReply.dart';

GlobalKey<_EcyConsignmentCommentPageState> consignmentCommentChildKey = GlobalKey();

class EcyConsignmentCommentPage extends StatefulWidget {
  late int productId;
  final Function(ConsignComment comment, ConsignReply? reply)
      onPressedCallback;

  EcyConsignmentCommentPage({
    required super.key,
    required this.productId,
    required this.onPressedCallback,
  });

  @override
  State<EcyConsignmentCommentPage> createState() => _EcyConsignmentCommentPageState(productId);

  void addComment(ConsignComment comment) {
    consignmentCommentChildKey.currentState?.addComment(comment);
  }

  void addReply(ConsignComment comment, ConsignReply reply) {
    consignmentCommentChildKey.currentState?.addReply(comment, reply);
  }

  void loadData() {
    consignmentCommentChildKey.currentState?._getCommentData();
  }
}

class _EcyConsignmentCommentPageState extends State<EcyConsignmentCommentPage> {
  _EcyConsignmentCommentPageState(this.productId);

  bool _loading = false;
  late int productId;
  int _total = 0;
  int _page = 0;
  List<ConsignComment> _commentList = [];

  @override
  void initState() {
    super.initState();

    _getCommentData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void addComment(ConsignComment comment) {
    comment.userName =
        EcyUserUtil.userModel.nickname ?? EcyUserUtil.userModel.username;
    comment.userImgUrl = EcyUserUtil.userModel.avatar??"";
    setState(() {
      _commentList.insert(0, comment);
    });
  }

  void addReply(ConsignComment comment, ConsignReply reply) {
    reply.userName =
        EcyUserUtil.userModel.nickname ?? EcyUserUtil.userModel.username;
    reply.userImgUrl = EcyUserUtil.userModel.avatar;
    reply.toUserName = reply.toUserName;
    if (comment.replyList == null) {
      comment.replyList = [reply];
    } else {
      comment.replyList?.insert(0, reply);
    }
    setState(() {});
  }

  void _getCommentData() async {
    if (_total != 0 && _page >= _total) {
      return;
    }
    Map<String, dynamic> body = {"productId": productId, "current": ++_page, "size": 6};
    var response = await EcyRequestbasemanager()
        .post("/app/api/app/consign/comment/page", body);
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EcyApiCommonPage<ConsignComment> commonPage =
            EcyApiCommonPage.fromJson(
                response["data"], (json) => ConsignComment.fromJson(json));

        _total = commonPage.pages ?? 0;
        _page = commonPage.current ?? 0;

        setState(() {
          _commentList.addAll(commonPage.records ?? []);
        });
      }
    }
  }

  Map<int, EcyApiCommonPage> pageMap = {};

  void _getReplayList(ConsignComment comment) async {
    if (_loading) {
      return;
    }
    _loading = true;

    try {
      EcyApiCommonPage commonPage = pageMap[comment.id!] ?? EcyApiCommonPage();
      var current = commonPage.current ??= 1;
      if (current > 1 && current > (commonPage.pages ?? 0)) {
        return;
      }

      Map<String, dynamic> body = {
        "commentId": comment.id,
        "current": current,
        "size": 3
      };
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/consign/replay/page", body);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<ConsignReply> replyPage =
              EcyApiCommonPage.fromJson(
                  response["data"], (json) => ConsignReply.fromJson(json));
          if (comment.replyList == null) {
            comment.replyList = replyPage.records ?? [];
          } else {
            comment.replyList?.addAll(replyPage.records ?? []);
          }
          setState(() {
            _commentList = _commentList;
          });

          commonPage.current = current + 1;
          commonPage.pages = replyPage.pages ?? 0;
          pageMap[comment.id!] = commonPage;
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
    } finally {
      _loading = false;
    }
  }

  Future<void> _onLike(
      int type, ConsignComment? comment, ConsignReply? reply) async {
    try {
      var loginFlag = await EcyUserUtil.logined();
      if (!loginFlag) {
        return;
      }
      Map<String, dynamic> body = {
        "type": type,
      };
      var commentFlag = type == 1;
      var likeFlag = false;
      var likeCount = 0;
      if (commentFlag) {
        likeFlag = !(comment?.like ?? false);
        likeCount = (comment?.likeCount ?? 0) + (likeFlag ? 1 : -1);
        comment?.like = likeFlag;
        comment?.likeCount = likeCount;
        body["commentReplayId"] = comment?.id;
      } else {
        likeFlag = !(reply?.like ?? false);
        likeCount = (reply?.likeCount ?? 0) + (likeFlag ? 1 : -1);
        reply?.like = likeFlag;
        reply?.likeCount = likeCount;
        body["commentReplayId"] = reply?.id;
      }
      body["like"] = likeFlag;
      setState(() {});
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/consign/like", body);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          return;
        }
        if (commentFlag) {
          comment?.like = !likeFlag;
          comment?.likeCount = likeCount + (likeFlag ? -1 : 1);
        } else {
          reply?.like = likeFlag;
          reply?.likeCount = likeCount + (likeFlag ? -1 : 1);
        }
        setState(() {});
        EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
      }
    } catch (e) {
      EcyLogger.log("点赞失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12),
      child: ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _commentList.length,
        itemBuilder: (context, index) {
          var comment = _commentList[index];
          var replyFlag =
              (comment.replyCount ?? 0) > (comment.replyList ?? []).length;
          return Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    width: 38.w,
                    height: 38.w,
                    child: CachedNetworkImage(
                        imageUrl: comment.userImgUrl ?? "",
                        imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(50.r)),
                                  image: DecorationImage(
                                      image: imageProvider, fit: BoxFit.cover)),
                            ),
                        errorWidget: (context, url, error) => ClipOval(
                            child: Image.asset("assets/images/app_icon.png"))),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width - 85.w,
                    child: Padding(
                      padding: const EdgeInsets.only(left: 5),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                comment.userName ?? "",
                                style: const TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14,
                                    color: Color(0xFF8C8C8C)),
                              ),
                            ],
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 5),
                            child: Text(
                              comment.content ?? "",
                              style: const TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w500,
                                  fontSize: 14,
                                  color: Color(0xFF262626)),
                            ),
                          ),
                          Row(
                            children: [
                              Text(
                                (comment.createTime ?? "刚刚")
                                    .replaceFirst("T", " "),
                                style: const TextStyle(
                                    color: Colors.grey, fontSize: 12),
                              ),
                              const Padding(padding: EdgeInsets.only(left: 30)),
                              GestureDetector(
                                  behavior: HitTestBehavior.translucent,
                                  onTap: () {
                                    widget.onPressedCallback(comment, null);
                                  },
                                  child: Row(
                                    children: [
                                      Image.asset(
                                        "assets/images/ic_comments.png",
                                        width: 12.w,
                                        height: 12.w,
                                      ),
                                      const Padding(
                                        padding: EdgeInsets.only(
                                          left: 2,
                                        ),
                                        child: Text(
                                          '回复',
                                          style: TextStyle(
                                              color: Colors.grey, fontSize: 12),
                                        ),
                                      ),
                                    ],
                                  )),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      _onLike(1, comment, null);
                    },
                    behavior: HitTestBehavior.translucent,
                    child: Column(
                      children: [
                        Image.asset(
                          comment.like ?? false
                              ? "assets/images/ic_thumbs_up.png"
                              : "assets/images/ic_thumbs_down.png",
                          scale: 2.2,
                        ),
                        Text(
                          '${comment.likeCount ?? 0}',
                          style: TextStyle(
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w500,
                              fontSize: 12.sp,
                              color: const Color(0xFF8C8C8C)),
                        ),
                      ],
                    ),
                  )
                ],
              ),
              const Padding(padding: EdgeInsets.only(top: 8)),
              ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: (comment.replyList ?? []).length,
                itemBuilder: (context, rIndex) {
                  var replay = (comment.replyList ?? [])[rIndex];
                  return Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Padding(padding: EdgeInsets.only(left: 38)),
                          SizedBox(
                            width: 38.w,
                            height: 38.w,
                            child: CachedNetworkImage(
                              imageUrl: replay.userImgUrl ?? "",
                              imageBuilder: (context, imageProvider) =>
                                  Container(
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(50.r)),
                                    image: DecorationImage(
                                        image: imageProvider,
                                        fit: BoxFit.cover)),
                              ),
                              errorWidget: (context, url, error) => ClipOval(
                                  child: Image.asset(
                                      "assets/images/app_icon.png")),
                            ),
                          ),
                          SizedBox(
                            width: MediaQuery.of(context).size.width - 123.w,
                            child: Padding(
                              padding: const EdgeInsets.only(left: 5),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        replay.userName ?? "未知",
                                        style: const TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 14,
                                            color: Color(0xFF8C8C8C)),
                                      ),
                                    ],
                                  ),
                                  Padding(
                                    padding:
                                        const EdgeInsets.symmetric(vertical: 5),
                                    child: replay.parentReplyId != null
                                        ? RichText(
                                            text: TextSpan(children: [
                                            const TextSpan(
                                              text: '回复 ',
                                              style: TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w500,
                                                  fontSize: 14,
                                                  color: Color(0xFF262626)),
                                            ),
                                            TextSpan(
                                              text: replay.toUserName,
                                              style: const TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w500,
                                                  fontSize: 14,
                                                  color: Color(0xFF8C8C8C)),
                                            ),
                                            TextSpan(
                                              text: '：${replay.content}',
                                              style: const TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w500,
                                                  fontSize: 14,
                                                  color: Color(0xFF262626)),
                                            ),
                                          ]))
                                        : Text(
                                            replay.content ?? '',
                                            style: const TextStyle(
                                                fontFamily: "PingFang SC",
                                                fontWeight: FontWeight.w500,
                                                fontSize: 14,
                                                color: Color(0xFF262626)),
                                          ),
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        (replay.createTime ?? "刚刚")
                                            .replaceFirst("T", " "),
                                        style: const TextStyle(
                                            color: Colors.grey, fontSize: 12),
                                      ),
                                      const Padding(
                                          padding: EdgeInsets.only(left: 30)),
                                      GestureDetector(
                                          behavior: HitTestBehavior.translucent,
                                          onTap: () {
                                            widget.onPressedCallback(
                                                comment, replay);
                                          },
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            children: [
                                              Image.asset(
                                                "assets/images/ic_comments.png",
                                                width: 12.w,
                                                height: 12.w,
                                              ),
                                              const Padding(
                                                padding: EdgeInsets.only(
                                                  left: 2,
                                                ),
                                                child: Text(
                                                  '回复',
                                                  style: TextStyle(
                                                      color: Colors.grey,
                                                      fontSize: 12),
                                                ),
                                              ),
                                            ],
                                          )),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              _onLike(2, null, replay);
                            },
                            behavior: HitTestBehavior.translucent,
                            child: Column(
                              children: [
                                Image.asset(
                                  replay.like ?? false
                                      ? "assets/images/ic_thumbs_up.png"
                                      : "assets/images/ic_thumbs_down.png",
                                  scale: 2.2,
                                ),
                                Text(
                                  '${replay.likeCount ?? 0}',
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 12.sp,
                                      color: const Color(0xFF8C8C8C)),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                      const Padding(padding: EdgeInsets.only(top: 8)),
                    ],
                  );
                },
              ),
              Align(
                alignment: Alignment.centerLeft,
                child: replyFlag
                    ? GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () {
                          _getReplayList(comment);
                        },
                        child: Padding(
                          padding: const EdgeInsets.only(left: 38, bottom: 20),
                          child: Text(
                            (comment.replyList ?? []).isEmpty
                                ? '展开${comment.replyCount ?? 0}条回复'
                                : '展开回复',
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w500,
                                fontSize: 12.sp,
                                color: const Color(0xFFEA4B9B)),
                          ),
                        ),
                      )
                    : Container(),
              ),
            ],
          );
        },
      ),
    );
  }

  // 弹出对话框
  Future<bool?> showDeleteConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
